<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">

      <el-form-item label="采购合同编号" prop="contractNumber">
        <el-input
          v-model="queryParams.contractNumber"
          placeholder="请输入采购合同编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="票据号" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入票据号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['purchase:purchaseOrder:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['purchase:purchaseOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="single"
          @click="handleAudit"
          v-hasPermi="['purchase:purchaseOrder:audit']"
        >审核</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['purchase:purchaseOrder:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchaseOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="票据号" align="center" prop="number" />
      <el-table-column label="采购合同编号" align="center" prop="contractNumber" />
      <el-table-column label="项目名" align="center" prop="projectName" />
      <el-table-column label="供应商" align="center" prop="companyName" />
<!--      <el-table-column label="项目代号" align="center" prop="projectCode" />-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="出入库时间" align="center" prop="operTime" width="180">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.operTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作员" align="center" prop="operName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.purchase_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="发货状态" align="center" prop="shippingStatus">
        <template slot-scope="scope">
          <el-select v-model="scope.row.shippingStatus" :value-key="scope.row.shippingStatus"
                     @change="updateStatus(scope.row)"
          >
            <el-option
              v-for="dict in dict.type.shipping_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
          <!--                <span>{{scope.row.name}}</span>-->
        </template>
      </el-table-column>
<!--      <el-table-column label="发货状态" align="center" prop="shippingStatus">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.shipping_status" :value="scope.row.shippingStatus"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="项目状态" align="center" prop="projectStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.project_status" :value="scope.row.projectStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['purchase:purchaseOrder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetails(scope.row)"
            v-hasPermi="['purchase:ryDepotHead:remove']"
          >详情
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改单据主表对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px">
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" :hide-required-asterisk="true">
        <el-row :gutter="10" class="mb8">
          <el-col :span="6">
            <el-form-item label="票据号" prop="number">
              <el-input v-model="form.number" placeholder="请输入票据号" :readonly="true"/>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="采购合同编号" prop="contractNumber">
              <el-input v-model="form.contractNumber" placeholder="请输入采购合同编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目关联" prop="linkHeadId">
              <el-select v-model="form.linkHeadId" clearable placeholder="请选择" @change="aa" :disabled="title === '修改采购订单'">
                <el-option
                  v-for="item in linkHeadOptions"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商" prop="organId">
              <el-select v-model="form.organId" clearable placeholder="请选择" @change="ab" :disabled="title === '修改采购订单'">
                <el-option
                  v-for="item in organOptions"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="5">
          <el-form-item label="交货时间">
            <el-date-picker
              :picker-options="pickerOptions"
              v-model="form.deliverTime"
              type="datetime"
              placeholder="选择交货时间">
            </el-date-picker>
          </el-form-item>
          </el-col>
          <el-col :span="6" v-if="title !=='添加采购订单'">
            <el-form-item label="创建时间:">
              <span>{{ parseTime(form.createTime) }}</span>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-button v-show="form.linkHeadId===undefined||form.linkHeadId===''" type="primary" @click="addRow()" style="margin-bottom: 10px">增加</el-button>
          <div style="width: 100%;overflow: auto hidden;text-align: center;margin-bottom: 60px">
            <el-table
              :data="tableData"
              style="width: 100%"
              border
              max-height="450"
            >
              <!--            <el-table :data="tableData" border style="max-height:calc(450px - 48px)">-->
              <el-table-column label="物品名称"  width="150" fixed>
                <template slot-scope="scope">
                  <el-input placeholder="请输入物品名称" v-model="scope.row.inventoryName">
                    <i slot="suffix" class="el-icon-search" @click="search(scope.row)" style="margin-top: 12px"></i>
                  </el-input>
                  <!--                  <span>{{scope.row.inventoryName}}</span>-->
                </template>
              </el-table-column>
              <el-table-column label="物品规格" fixed>
                <template slot-scope="scope">
                  <!--                <el-input placeholder="请输入物品规格" v-model="scope.row.inventorySpecifications"></el-input>-->
                  <span>{{ scope.row.inventorySpecifications }}</span>
                </template>
              </el-table-column>
              <el-table-column label="供应商">
                <template slot-scope="scope">
                  <el-input placeholder="请输入供应商" v-model="scope.row.supply"></el-input>
                  <!--                <span>{{scope.row.supply}}</span>-->
                </template>
              </el-table-column>
              <el-table-column label="wbs编码">
                <template slot-scope="scope">
                  <el-input placeholder="请输入wbs编码" v-model="scope.row.wbs"></el-input>
                  <!--                <span>{{scope.row.wbs}}</span>-->
                </template>
              </el-table-column>
              <el-table-column label="单价">
                <template slot-scope="scope">
                  <el-input placeholder="请输入单价" v-model="scope.row.unitPrice"></el-input>
                  <!--                <span>{{scope.row.wbs}}</span>-->
                </template>
              </el-table-column>
              <el-table-column label="备注">
                <template slot-scope="scope">
                  <el-input placeholder="请输入备注" v-model="scope.row.remark"></el-input>
                  <!--                <span>{{scope.row.remark}}</span>-->
                </template>
              </el-table-column>
              <el-table-column prop="advancePurchaseNum" label="待采购数量"></el-table-column>
              <el-table-column label="总库可用数量">
                <template slot-scope="scope">
                  <!--                  <el-input placeholder="请输入备注" v-model="scope.row.advancePurchaseNum"></el-input>-->
                  <span>{{scope.row.usableNum}}</span>
                </template>
              </el-table-column>
              <el-table-column label="实际采购数量">
                <template slot-scope="scope">
                  <!--                  <el-input placeholder="请输入采购数量" v-model="scope.row.actualPurchaseNum"></el-input>-->
                  <!--                <span>{{scope.row.name}}</span>-->
                  <el-input-number placeholder="请输入采购数量" v-model="scope.row.actualPurchaseNum" style="width: 50px;text-align: left;padding: 0px 0px"
                                   size="small" :controls="false"
                                   :max="scope.row.advancePurchaseNum === 0 ? 10000 : scope.row.advancePurchaseNum" :min="0"></el-input-number>
                </template>
              </el-table-column>
<!--              <el-table-column label="发货状态">-->
<!--                <template slot-scope="scope">-->
<!--                  <el-select v-model="scope.row.shippingStatus" placeholder="请选择发货状态">-->
<!--                    <el-option-->
<!--                      v-for="dict in dict.type.shipping_status"-->
<!--                      :key="dict.value"-->
<!--                      :label="dict.label"-->
<!--                      :value="dict.value"-->
<!--                    ></el-option>-->
<!--                  </el-select>-->
<!--                  &lt;!&ndash;                <span>{{scope.row.name}}</span>&ndash;&gt;-->
<!--                </template>-->
<!--              </el-table-column>-->

              <el-table-column  label="操作" fixed="right"  >
                <template slot-scope="scope" >
                  <el-popconfirm title="确定删除吗？" @confirm="deleteRow(scope)">
                    <el-button  v-show="form.linkHeadId===undefined||form.linkHeadId===''" type="primary" slot="reference" >删除</el-button>
                  </el-popconfirm>

                </template>
              </el-table-column>
            </el-table>
          </div>
<!--          <div style="text-align: center;font-size: 20px;margin-bottom: 20px">关联项目</div>-->
<!--          <div style="width: 100%;overflow: auto hidden;text-align: center">-->
<!--            <el-table-->
<!--              :data="projectTableData"-->
<!--              style="width: 100%"-->
<!--              border-->
<!--              max-height="450"-->
<!--            >-->
<!--              <el-table-column prop="inventoryName" label="物品名称"  width="150" fixed></el-table-column>-->
<!--              <el-table-column prop="inventorySpecifications" label="物品规格"  width="150" fixed></el-table-column>-->
<!--              <el-table-column prop="supply" label="供应商"></el-table-column>-->
<!--              <el-table-column prop="wbs" label="wbs编码"></el-table-column>-->
<!--              <el-table-column prop="remark" label="备注"></el-table-column>-->
<!--              <el-table-column prop="advancePurchaseNum" label="待采购数量"></el-table-column>-->
<!--              <el-table-column prop="actualPurchaseNum" label="实际采购数量"></el-table-column>-->

<!--              <el-table-column prop="shippingStatus" label="发货状态"></el-table-column>-->

<!--              <el-table-column prop="purchaseMan" label="采购员"></el-table-column>-->
<!--              <el-table-column prop="qualifiedNum" label="合格数量"></el-table-column>-->
<!--              <el-table-column prop="unqualifiedNum" label="不合格数量"></el-table-column>-->
<!--              <el-table-column prop="unqualifiedReason" label="不合格原因"></el-table-column>-->

<!--              <el-table-column prop="returnStatus" label="退回状态"></el-table-column>-->

<!--              <el-table-column prop="retransmissionStatus" label="重发状态"></el-table-column>-->

<!--              <el-table-column prop="retransmissionNum" label="重发数量"></el-table-column>-->
<!--              <el-table-column prop="qualityInspector" label="质检员"></el-table-column>-->
<!--              <el-table-column prop="qualityTime" label="质检时间"></el-table-column>-->
<!--              <el-table-column prop="inNum" label="入库数量"></el-table-column>-->
<!--              <el-table-column prop="inDepot" label="入库仓库"></el-table-column>-->
<!--              <el-table-column prop="location" label="库位"></el-table-column>-->
<!--              <el-table-column prop="inOperateMan" label="入库操作员"></el-table-column>-->
<!--              <el-table-column prop="inTime" label="入库时间"></el-table-column>-->
<!--              <el-table-column prop="outNum" label="出库数量"></el-table-column>-->
<!--              <el-table-column prop="outDepot" label="出库仓库"></el-table-column>-->
<!--              <el-table-column prop="outOperateMan" label="出库操作员"></el-table-column>-->
<!--              <el-table-column prop="outOperateMan" label="领用人"></el-table-column>-->
<!--              <el-table-column prop="outTime" label="出库时间"></el-table-column>-->
<!--              <el-table-column prop="transferNum" label="转移数量"></el-table-column>-->

<!--            </el-table>-->
<!--          </div>-->
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="form.remark"></el-input>
        </el-form-item>
        <el-form-item label="附件名称">
          <file-upload v-model="form.fileName"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      <!--      物品列表-->
      <el-dialog
        width="65%"
        title="物品信息"
        :visible.sync="goodsDetailsStatus"

        append-to-body>
        <el-form :model="goodsQueryParams" size="small" label-width="100px">
          <el-row :gutter="10" class="mb8">
            <el-col :span="6">
              <el-form-item label="物品名称" prop="projectCode">
                <el-input
                  v-model="goodsQueryParams.name"
                  placeholder="请输入物品名称"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="goodsQuery">搜索</el-button>
            </el-col>
          </el-row>

        </el-form>

        <el-table v-loading="loading" max-height="450" :data="RyInventoryList">
          <!--      <el-table-column label="主键" align="center" prop="id" />-->
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="规格" align="center" prop="specifications" />
          <el-table-column label="wbs编码" align="center" prop="wbs" />
          <el-table-column label="品牌" align="center" prop="brand" />
          <el-table-column label="图片" align="center" prop="images" width="100">
            <template slot-scope="scope">
              <image-preview :src="scope.row.images" :width="50" :height="50"/>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" prop="unit">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.ware_inventory_unit" :value="scope.row.unit"/>
            </template>
          </el-table-column>
          <el-table-column label="单价(元)" align="center" prop="unitPrice" />
          <el-table-column label="供应商" align="center" prop="supply" />
          <el-table-column label="库位" align="center" prop="location" />
          <el-table-column label="操作人/经办人" align="center" prop="operator" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="primary" @click="goodsChange(scope.row)">选中</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="goodsTotal>0"
          :total="goodsTotal"
          :page.sync="goodsQueryParams.pageNum"
          :limit.sync="goodsQueryParams.pageSize"
          @pagination="search(undefined)"
        />
      </el-dialog>
    </el-dialog>
    <!--    详情弹窗-->
    <el-dialog :title="title" :visible.sync="details" width="1200px">
      <el-form ref="form" :model="form" label-width="100px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="6">
            <el-form-item label="票据号: ">
              <!--              <el-input v-model="form.projectName" placeholder="请输入项目名"/>-->
              <span>{{form.number}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="采购合同编号: ">
              <!--              <el-input v-model="form.projectCode" placeholder="请输入项目代号"/>-->
              <span>{{form.contractNumber}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6" v-show="form.projectName !== null">
            <el-form-item label="项目关联: ">
              <!--              <el-input v-model="form.contractNumber" placeholder="请输入采购合同编号"/>-->
              <span>{{form.projectName}}</span>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商: ">
              <!--              <el-input v-model="form.number" placeholder="请输入票据号"/>-->
              <span>{{ form.companyName}}</span>

            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="6">
            <el-form-item label="创建时间:">
              <span>{{ parseTime(form.createTime) }}</span>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="10" class="mb8" v-show="false">
          <div style="width: 100%;overflow-x: auto;text-align: center">
            <el-table :data="tableData" border max-height="450" ref="report-table">
              <el-table-column label="票据号">
                <el-table-column prop="inventoryName" label="物品名称" width="150"></el-table-column>
                <el-table-column prop="inventorySpecifications" label="物品规格"></el-table-column>

              </el-table-column>

              <el-table-column :label="form.number">
                <el-table-column prop="supply" label="供应商"></el-table-column>
              </el-table-column>

              <el-table-column label="采购合同编号" >
                <el-table-column prop="wbs" label="wbs编码"></el-table-column>
              </el-table-column>

              <el-table-column  :label="form.contractNumber" >
                <el-table-column prop="remark" label="备注"></el-table-column>
              </el-table-column>


              <el-table-column v-if="form.projectName!==null" label="项目关联">
                <el-table-column prop="advancePurchaseNum" label="待采购数量"></el-table-column>
              </el-table-column>
              <el-table-column v-else >
                <el-table-column prop="advancePurchaseNum" label="待采购数量"></el-table-column>
              </el-table-column>

              <el-table-column v-if="form.projectName!==null" :label="form.projectName">
                <el-table-column prop="usableNum" label="总库可用数量"></el-table-column>
              </el-table-column>
              <el-table-column v-else>
                <el-table-column prop="usableNum" label="总库可用数量"></el-table-column>
              </el-table-column>


              <el-table-column label="供应商">
                <el-table-column prop="actualPurchaseNum" label="实际采购数量"></el-table-column>

              </el-table-column>

<!--              <el-table-column :label="form.companyName">-->
<!--                <el-table-column label="发货状态">-->
<!--                  <template slot-scope="scope">-->
<!--                    <span v-for="(item) in dict.type.shipping_status" v-if="scope.row.shippingStatus === item.value">-->
<!--                    {{item.label}}-->
<!--                  </span>-->
<!--                  </template>-->

<!--                </el-table-column>-->
<!--              </el-table-column>-->

            </el-table>
          </div>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <div style="width: 100%;overflow-x: auto;text-align: center">
            <el-table :data="tableData" border>
              <el-table-column prop="inventoryName" label="物品名称" width="150"></el-table-column>
              <el-table-column prop="inventorySpecifications" label="物品规格" width="150"></el-table-column>
              <el-table-column prop="supply" label="供应商"></el-table-column>
              <el-table-column prop="wbs" label="wbs编码"></el-table-column>
              <el-table-column prop="remark" label="备注"></el-table-column>
              <el-table-column prop="advancePurchaseNum" label="待采购数量"></el-table-column>
              <el-table-column prop="usableNum" label="总库可用数量"></el-table-column>
              <el-table-column prop="actualPurchaseNum" label="实际采购数量"></el-table-column>
<!--              <el-table-column label="发货状态">-->
<!--                <template slot-scope="scope">-->
<!--                    <span v-for="(item) in dict.type.shipping_status" v-if="scope.row.shippingStatus === item.value">-->
<!--                    {{item.label}}-->
<!--                  </span>-->
<!--                </template>-->
<!--              </el-table-column>-->

            </el-table>
          </div>
        </el-row>
      </el-form>
      <div slot="footer" style="text-align: center">
        <el-button type="success" size="medium" @click="exportExcel">导出</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchaseOrder, getPurchaseOrder, delPurchaseOrder, addPurchaseOrder, updatePurchaseOrder } from "@/api/purchase/purchaseOrder";
import { listRyInventory } from '@/api/inventory/RyInventory'
import axios from 'axios'
import * as XLSX from 'xlsx/xlsx.mjs'
import * as FileSaver from 'file-saver'
import { formatDatee } from '@/utils'
import request from '@/utils/request'
import print from 'print-js'
import {updateRyDepotHead} from "@/api/purchase/ryDepotHead";

export default {
  name: "PurchaseOrder",
  dicts: ['project_status', 'shipping_status','purchase_status'],
  data() {
    return {
      ip: 'http://localhost:8080',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      purchaseOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        projectCode: null,
        contractNumber: null,
        number: null,
        status: null,
        projectStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractNumber: [
          { required: true, message: '请输入采购合同编号', trigger: 'blur' }
        ],
        number: [
          { required: true, message: '请输入采购订单编号', trigger: 'blur' }
        ],
        organId: [
          { required: true, message: '请输入供应商', trigger: 'change' }
        ],
      },
      // 新增物品弹窗展示
      goodsDetailsStatus: false,
      // 下拉框查询参数
      params : {},
      // 关联项目下拉框
      linkHeadOptions: [],
      // 供应商下拉框
      organOptions: [],
      // 选中的物品信息
      RyInventoryList: [],
      // 新增/修改弹窗表格数据
      tableData: [],
      // 详情页弹窗状态
      details: false,
      // 新增物品弹窗 表格分页
      goodsTotal: 0,
      goodsQueryParams: {
        pageNum: 1,
        pageSize: 5,
        name: null,
        projectCode: null,
        contractNumber: null,
        number: null,
        status: null,
        projectStatus: null
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      }
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询采购订单列表 */
    getList() {
      this.loading = true;
      listPurchaseOrder(this.queryParams).then(response => {
        console.log(response)
        this.purchaseOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectName: null,
        projectCode: null,
        depotId: null,
        contractNumber: null,
        type: null,
        subType: null,
        defaultNumber: null,
        number: null,
        createTime: null,
        operTime: null,
        organId: null,
        creator: null,
        billType: null,
        remark: null,
        fileName: null,
        salesMan: null,
        status: null,
        projectStatus: null,
        linkNumber: null,
        tenantId: null,
        delFlag: null
      };
      this.tableData = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.form.number = 'CGDD'+formatDatee()
      this.form.createTime = new Date()
      console.log(this.form.createTime)
      this.title = '添加采购订单'

     this.getOptions()

      // this.reset();
      // this.open = true;
      // this.title = "添加采购订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let that =this
      console.log(row.projectStatus)
      if (row.projectStatus === '1') {
        that.$message({
          showClose: true,
          message: '项目已结束',
          type: 'warning'
        })
      } else {
        this.reset();
        const id = row.id || this.ids
        return request({
          url: '/purchase/purchaseOrder/selectRyDepotDetailById/' + id,
          method: 'get'
        }).then(function (res) {
          console.log(res)
          if (res.code === 200) {
            that.open = true
            that.title = '修改采购订单'
            that.form = res.data
            that.tableData = res.data.tableData
            that.getOptions()
          }
        })
      }
    },
    // 详情按钮
    handleDetails(row){
      let that = this
      return request({
        url: '/purchase/purchaseOrder/selectRyDepotDetailById/' + row.id,
        method: 'get'
      }).then(function(res) {
        console.log(res)
        if (res.code === 200) {
          that.details = true
          that.title = '采购订单详情';
          that.form = res.data;
          that.tableData = res.data.tableData;
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      let that = this
      this.form.tableData = this.tableData
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePurchaseOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            return request({
              url: '/purchase/purchaseOrder/addDepotHeadAndDetail',
              method: 'post',
              data: this.form
            }).then(function(res) {
              console.log(res)
              if (res.code === 200) {
                that.$message({
                  showClose: true,
                  message: '新增成功',
                  type: 'success'
                })
                that.open = false
                that.getList()
              } else {
                console.log('报错了')
                that.$message({
                  showClose: true,
                  message: res.msg,
                  duration: 0,
                  type: 'warning'
                })
              }
            }).catch(res => {
              console.log(res)
            })

            // addPurchaseOrder(this.form).then(response => {
            //   this.$modal.msgSuccess("新增成功");
            //   this.open = false;
            //   this.getList();
            // });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除采购订单编号为"' + ids + '"的数据项？').then(function() {
        return delPurchaseOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('purchase/purchaseOrder/export', {
        ...this.queryParams
      }, `purchaseOrder_${new Date().getTime()}.xlsx`)
    },
    //删除行
    deleteRow(data) {
      this.tableData.splice(data.$index, 1)
    },
    //增加行
    addRow() {
      let newRow = {  }
      this.tableData.splice(this.tableData.length, 0, newRow)
    },
    // 获取物品信息
    search(row){
      if (row === undefined || row.id === undefined){
        this.goodsDetailsStatus = true
        listRyInventory(this.goodsQueryParams).then(res => {
          this.RyInventoryList = res.rows
          this.goodsTotal = res.total;
          this.goodsQueryParams.name = ''
          console.log(res.rows)
        })
      }
    },
    // 物品详情表格的点击事件
    goodsChange(row){
      console.log(row)
      let that =this
      axios({
        url:this.ip + '/infc/getInfoByInventory',
        method: 'post',
        // responseType: 'json',
        contentType: 'application/json,charset=UTF-8 ',
        data: row
      }).then(function(res) {
        let arr =[]
        for (let i = 0; i < that.tableData.length-1; i++) {
          arr.push( that.tableData[i])
        }
        arr.push(res.data.data)
        that.tableData = arr

        that.goodsDetailsStatus = false
      })
    },
    // 物品信息搜索
    goodsQuery() {
      this.goodsQueryParams.pageNum = 1
      this.search()
    },
    //项目关联下拉框
    aa(e){
      let that = this
      if (e !== '' && e !== undefined){
        return request({
          url: '/purchase/ryDepotDetail/selectDetailForOrder',
          method: 'get',
          params: {linkHeadId:that.form.linkHeadId,organId:that.form.organId},
        }).then(function(res) {
          if (res.code === 200){
            that.tableData = res.data
          }
        })
      }else{
        that.tableData = []
      }

    },
    //供应商下拉框
    ab(e){
      let that = this
      if (e !== ''){
        console.log("linkHeadId---->"+that.form.linkHeadId);
        //关联项目可能为空或者undefined情况;
        // 1.当点击新增按钮并且在弹出页面中没有操作关联项目下拉框时为undefined,
        // 2.当点击新增按钮并且在弹出页面中操作了关联项目下拉框然后清除掉的数据为''
        if(that.form.linkHeadId === undefined || that.form.linkHeadId === ''){
          console.log("lll2222222");
          return;
        }
        console.log(that.form.linkHeadId)
        return request({
          url: '/purchase/ryDepotDetail/selectDetailForOrder',
          method: 'get',
          params: {linkHeadId:that.form.linkHeadId,organId:that.form.organId},
        }).then(function(res) {
          if (res.code === 200){
            that.tableData = res.data
          }
        })
      }
    },
    printBox() {
      setTimeout(function() {
        print({
          printable: 'printBox',	//打印区域id
          type: 'html',		//打印类型是html
          scanStyles: false,
          targetStyles: ['*'],
        })
      }, 500)
    },
    exportExcel() {
      try {
        const $e = this.$refs['report-table'].$el
        let $table = $e.querySelector('.el-table__fixed')
        if(!$table) {
          $table = $e
        }

        const wb = XLSX.utils.table_to_book($table, {raw:true})
        const wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST:true, type: 'array'})
        FileSaver.saveAs(
          new Blob([wbout],{type: 'application/octet-stream'}),
          `采购详情.xlsx`,
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.error(e)
      }
    },
    // 获取关联项目和供应商下拉框信息
    getOptions(){
      let that = this;
      return request({
        url: '/purchase/ryDepotHead/all',
        method: 'get'
      }).then(function(res) {
        return request({
          url: '/information/tbCustomers/CompanyTypeAll/' + 0,
          method: 'get'
        }).then(function(ress) {
          that.linkHeadOptions = res.data
          that.organOptions = ress.data
          console.log(res);
          console.log(ress);
        })

      })
    },
    //更改发货状态
    updateStatus(row) {
      if (row.projectStatus === '1') {
        this.$message({
          showClose: true,
          message: '项目已结束',
          type: 'warning'
        })
        return;
      }
      //新建更新参数，以防修改其他不相关数据
      let newRow = {};
      newRow.id = row.id;
      newRow.shippingStatus = row.shippingStatus;
      this.$confirm('是否确认更改发货状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateRyDepotHead(newRow).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.getList()
        })
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // });
      }).catch(() => {
        this.getList()
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      })

    },
    //审核
    handleAudit(row) {
      console.log("ids---" + this.ids[0]);
      let rowData={};
      for(let i = 0; i < this.purchaseOrderList.length; i++){
        if(this.ids[0] === this.purchaseOrderList[i].id){
          rowData = this.purchaseOrderList[i];
          // console.log("----------" + this.purchaseOrderList[i].id);
        }
      }

      if (rowData.projectStatus === '1') {
        this.$message({
          showClose: true,
          message: '项目已结束',
          type: 'warning'
        })
        return;
      }
      if (rowData.status === '1') {
        this.$message({
          showClose: true,
          message: '单据已审核',
          type: 'warning'
        })
        return;
      }
      //新建更新参数，以防修改其他不相关数据
      let newRow = {};
      newRow.id = rowData.id;
      //设置单据状态为需要修改的值，1为已审核
      newRow.status = '1'
      this.$confirm('是否确认更改审核状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        updateRyDepotHead(newRow).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.getList()
        })
        // this.$message({
        //   type: 'success',
        //   message: '删除成功!'
        // });
      }).catch(() => {
        this.getList()
        // this.$message({
        //   type: 'info',
        //   message: '已取消删除'
        // });
      })

    },
  }
};
</script>
